package com.ls.demo.http.handler;

import com.google.gson.Gson;
import com.ls.demo.bean.RoomInfo;
import com.ls.demo.http.config.HttpServerProperties;
import com.ls.demo.tcp.service.DispatcherCommand;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 接受设备调整参数
 * @author liShan
 * @date 2019/8/31 15:11
 */
@Component
@ChannelHandler.Sharable
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Resource
    private HttpServerProperties properties;

    @Resource
    private DispatcherCommand dispatcherCommand;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
        FullHttpResponse resp ;
        try{
            ByteBuf buf = msg.content();
            String str;
            // 处理堆缓冲区
            if(buf.hasArray()) {
                str = new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
            } else {
                // 处理直接缓冲区以及复合缓冲区
                byte[] bytes = new byte[buf.readableBytes()];
                buf.getBytes(buf.readerIndex(), bytes);
                str = new String(bytes, 0, buf.readableBytes());
            }
            dispatcherCommand.downloadCommand(str, msg.uri());
            resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    Unpooled.copiedBuffer("{\"statusCode\":2000,\"message\":\"成功\"}", CharsetUtil.UTF_8));
            resp.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        }catch (Exception e){
            e.printStackTrace();
            resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    Unpooled.copiedBuffer("{\"statusCode\":5000,\"message\":\""+e.getMessage()+"\"}", CharsetUtil.UTF_8));
            resp.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        }
        ctx.writeAndFlush(resp)
                .addListener( future -> ctx.close());

    }

}
